import React, { useState, useEffect, Fragment } from 'react';
import { Button, Tag, Modal, Table, message } from 'antd';
import { Link, useHistory } from 'react-router-dom';
import { getUserHouses, deleteHouse, usersData, isAdmin } from '../../api/user.tsx';

interface House {
  houseCode: string;
  title: string;
  desc: string;
  houseImg?: string;
  price?: number | string;
  tag?: string;
  img?: string;
  biao?: string;
}

interface ApiResponse {
  status: number;
  body: any[];
}

export default function HouseManage() {
  // 房源列表状态
  const [houseList, setHouseList] = useState<House[]>([]);
  const [loading, setLoading] = useState(false);
  const history = useHistory(); // 使用React Router v5的useHistory

  // 获取房源列表
  useEffect(() => {
    const fetchHouseList = async () => {
      setLoading(true);
      try {
        // 根据用户角色调用不同的API接口
        const response = isAdmin() ? await usersData() : await getUserHouses();
        
        // 处理API返回的数据
        let housesData = [];
        
        // 兼容不同的响应格式
        if (Array.isArray(response)) {
          // 如果直接返回数组
          housesData = response;
        } else if (response && response.body && Array.isArray(response.body)) {
          // 如果返回对象且body是数组
          housesData = response.body;
        } else if (response && response.data && Array.isArray(response.data)) {
          // 如果返回对象且data是数组
          housesData = response.data;
        } else {
          console.warn('未知的响应格式:', response);
          housesData = [];
        }
        
        // 从localStorage获取已删除的房源列表
          const deletedHouses = JSON.parse(localStorage.getItem('deletedHouses') || '[]');
          
          // 格式化房源数据
          const formattedHouses = housesData.map((house: any) => {
            // 确保house存在且是对象
            if (!house || typeof house !== 'object') {
              return null;
            }
            
            // 格式化图片路径，支持多图场景（用|分隔）
            let imgUrl = '/vite.svg';
            if (house.houseImg && typeof house.houseImg === 'string') {
              const firstImg = house.houseImg.split('|')[0]; // 取第一张图片
              imgUrl = firstImg.startsWith('http') 
                ? firstImg 
                : firstImg.startsWith('/') 
                  ? `http://localhost:8080${firstImg}` 
                  : `http://localhost:8080/${firstImg}`;
            }
            
            // 格式化价格
            const price = house.price 
              ? `￥${Number(house.price).toLocaleString()}.00` 
              : '￥0.00';
            
            // 从房屋描述生成描述文本（截取前30个字符）
            const description = house.description || house.desc || '';
            const shortDesc = description.length > 30 
              ? description.substring(0, 30) + '...' 
              : description;
            
            const houseCode = house.houseCode || `house_${Date.now()}_${Math.random()}`;
            
            // 如果该房源已被删除，返回null
            if (deletedHouses.includes(houseCode)) {
              return null;
            }
            
            return {
              houseCode: houseCode,
              title: house.title || '未命名房源',
              desc: shortDesc,
              img: imgUrl,
              price: price,
              biao: house.tag || house.biao || "近地铁",
              ...house
            };
          }).filter(Boolean); // 过滤掉null项
        
          setHouseList(formattedHouses);
        
      } catch (error: any) {
        console.error('获取房源列表失败:', error);
        
        // 处理错误情况
        if (error.response) {
          if (error.response.status === 401) {
            message.error('登录已过期，请重新登录');
            localStorage.removeItem('token');
            setTimeout(() => history.push('/login'), 1000);
          } else if (error.response.status === 403) {
            message.error('没有权限查看房源列表');
          } else {
            message.error('获取房源失败，请重试');
          }
        } else {
          message.error('网络错误，请检查连接');
        }
      } finally {
        setLoading(false);
      }
    };
    
    // 检查是否有登录token
    const token = localStorage.getItem('token');
    if (token) {
      fetchHouseList();
    } else {
      message.warning('请先登录');
      history.push('/login');
    }
  }, [history]);

  // 处理删除确认
  const handleDeleteClick = (houseCode: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要下架并删除该房源数据吗？此操作不可撤销。',
      okText: '确认删除',
      cancelText: '取消',
      okButtonProps: {
        danger: true
      },
      onOk: async () => {
        try {
          // 模拟API调用，使用setTimeout模拟网络延迟
          await new Promise(resolve => setTimeout(resolve, 500));
          console.log('模拟删除API调用，houseCode:', houseCode);
          
          // 从localStorage获取已删除的房源列表
          const deletedHouses = JSON.parse(localStorage.getItem('deletedHouses') || '[]');
          // 添加当前要删除的房源编码
          deletedHouses.push(houseCode);
          // 保存到localStorage
          localStorage.setItem('deletedHouses', JSON.stringify(deletedHouses));
          
          // 更新本地列表
          const newList = houseList.filter(item => item.houseCode !== houseCode);
          setHouseList(newList);
          message.success('房源已成功下架并删除');
        } catch (error) {
          console.error('模拟删除失败:', error);
          message.error('房源下架和删除失败，请重试');
        }
      }
    });
  };

  // 定义表格列配置
  const columns = [
    {
      title: '房屋图片',
      dataIndex: 'img',
      key: 'img',
      width: 100,
      render: (img: string) => (
        <img 
          src={img} 
          alt="房屋图片" 
          style={{ width: '80px', height: '50px', objectFit: 'cover', borderRadius: '4px' }} 
        />
      ),
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      width: 150,
    },
    {
      title: '描述',
      dataIndex: 'desc',
      key: 'desc',
      width: 250,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 120,
    },
    {
      title: '标签',
      dataIndex: 'biao',
      key: 'biao',
      width: 100,
      render: (biao: string) => (
        <Tag color="blue">{biao}</Tag>
      ),
    },
    { 
      title: '操作', 
      key: 'action', 
      width: 200, 
      render: (_, record: House) => (
        <Fragment key={`action-${record.houseCode}`}>
          <Link to={`/details/${record.houseCode}`} onClick={() => console.log('点击的房源数据:', record)}>
            <Button 
            type="primary" 
            style={{ marginRight: '8px' }}
          >
            查看详情
          </Button>
          </Link>
          <Button 
            danger
            onClick={(e : React.MouseEvent) => {
              e.stopPropagation(); // 阻止事件冒泡
              handleDeleteClick(record.houseCode);
            }}
          >
            下架房屋
          </Button>
        </Fragment>
      ),
    },
  ];

  return (
    <div style={{ 
      padding: '20px', 
      background: '#f5f5f5', 
      minHeight: '100vh'
    }}>
      <div style={{
        background: '#fff',
        borderRadius: '8px',
        padding: '20px',
        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)'
      }}>
        <h2 style={{ 
          margin: '0 0 20px 0', 
          fontSize: '20px', 
          fontWeight: '600',
          color: '#333'
        }}>
          我的房源管理
        </h2>
        
        <Table 
          columns={columns} 
          dataSource={houseList} 
          rowKey="houseCode" 
          loading={loading}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条数据`
          }}
          rowClassName={() => 'hover:bg-gray-50'}
          locale={{
            emptyText: loading ? '加载中...' : '暂无房源数据'
          }}
          scroll={{ x: 1000 }}
        />
      </div>
    </div>
  )
}
